import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../models/gb_channel_model.dart';
import '../../../services/gb_video_service.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../providers/system_provider.dart';
import '../../../translations/app_translations.dart';
import '../../../routes/app_routes.dart';

class DeviceChannelView extends StatefulWidget {
  const DeviceChannelView({Key? key}) : super(key: key);

  @override
  State<DeviceChannelView> createState() => _DeviceChannelViewState();
}

class _DeviceChannelViewState extends State<DeviceChannelView> {
  // 通道列表
  List<GBChannel> _channels = [];
  
  // 状态标志
  bool _isLoading = false;
  bool _isError = false;
  bool _isLoggedIn = false;
  String _errorMessage = '';
  
  // 设备信息
  late final int _deviceId;
  late final String _deviceName;
  late final String _wvpDeviceId;
  String? _gbDeviceId;
  
  // 服务实例
  final GBVideoService _gbVideoService = Get.find<GBVideoService>();
  final SystemProvider _systemProvider = SystemProvider();
  
  @override
  void initState() {
    super.initState();
    
    // 获取传入的参数
    final args = Get.arguments as Map<String, dynamic>? ?? {};
    _deviceId = args['deviceId'] ?? 0;
    _deviceName = args['deviceName'] ?? 'Unknown Device';
    _wvpDeviceId = args['wvpDeviceId'] ?? '';
    
    debugPrint('==== 通道列表页面初始化 ====');
    debugPrint('设备ID: $_deviceId');
    debugPrint('设备名称: $_deviceName');
    debugPrint('国标设备ID: "$_wvpDeviceId"');
    
    // 初始化检查
    _initialize();
  }
  
  // 初始化：检查登录状态并加载数据
  Future<void> _initialize() async {
    setState(() {
      _isLoading = true;
      _isError = false;
    });
    
    try {
      // 检查国标ID是否为空
      if (_wvpDeviceId.isEmpty) {
        setState(() {
          _isLoading = false;
          _isError = true;
          _errorMessage = LocaleKeys.getStreamFailed.tr;
        });
        return;
      }
      
      // 检查是否已登录WVP平台
      if (!_gbVideoService.isLoggedIn.value) {
        debugPrint('未登录WVP平台，尝试登录...');
        // 尝试登录WVP平台
        final success = await _gbVideoService.login('admin', '21232f297a57a5a743894a0e4a801fc3');
        if (!success) {
          setState(() {
            _isLoading = false;
            _isError = true;
            _errorMessage = LocaleKeys.loginVideoFailed.tr;
          });
          return;
        }
        debugPrint('登录WVP平台成功');
      } else {
        debugPrint('已登录WVP平台');
      }
      
      // 设置登录状态
      _isLoggedIn = true;
      
      // 使用设备的国标ID
      _gbDeviceId = _wvpDeviceId;
      debugPrint('使用设备ID: $_gbDeviceId把通道列表显示在页面上！！！');
      
      // 使用SystemProvider获取通道列表
      try {
                  // 步骤1：获取WVP设备信息
        final gbDeviceInfo = await _systemProvider.getGBDeviceInfo(_wvpDeviceId);
        
        if (gbDeviceInfo['code'] == 200 && gbDeviceInfo['rows'] != null && gbDeviceInfo['rows'].isNotEmpty) {
          final gbDevice = gbDeviceInfo['rows'][0];
          final gbDeviceId = gbDevice['id'].toString(); // 确保ID是字符串
          
          debugPrint('WVP设备信息解析成功:');
          debugPrint('- 主键ID: $gbDeviceId');
          debugPrint('- 名称: ${gbDevice['name']}');
          debugPrint('- 设备国标ID: ${gbDevice['deviceId']}');
          debugPrint('- 厂商: ${gbDevice['manufacturer']}');
          debugPrint('- 型号: ${gbDevice['model']}');
          
          // 步骤2：获取通道列表
          final channelListResponse = await _systemProvider.getGBChannelList(gbDeviceId);
          
          if (channelListResponse['code'] == 200 && channelListResponse['rows'] != null) {
            final channelList = channelListResponse['rows'];
            
            debugPrint('通道列表解析成功，显示在页面上:');
            debugPrint('- 通道数量: ${channelList.length}');
            
            // 处理通道列表并显示详细信息
            _channels = [];
            for (var channel in channelList) {
              try {
                // 打印原始的ptzType值用于调试
                debugPrint('通道原始ptzType值: ${channel['ptzType']} (类型: ${channel['ptzType']?.runtimeType})');
                
                // 使用fromJson方法创建GBChannel对象
                final gbChannel = GBChannel.fromJson(channel);
                
                _channels.add(gbChannel);
                
                // 打印通道详细信息
                debugPrint('------- 通道${_channels.length} -------');
                debugPrint('通道ID: ${gbChannel.id}');
                debugPrint('国标ID: ${gbChannel.deviceId}');
                debugPrint('名称: ${gbChannel.name}');
                debugPrint('状态: ${gbChannel.status}');
                debugPrint('厂商: ${gbChannel.manufacturer}');
                debugPrint('型号: ${gbChannel.model}');
                debugPrint('位置: ${gbChannel.address}');
                debugPrint('云台类型: ${gbChannel.ptzType}');
              } catch (e) {
                debugPrint('处理通道数据出错: $e');
              }
            }
          } else {
            debugPrint('未找到通道或响应格式不正确');
            _channels = [];
          }
        } else {
          debugPrint('未找到WVP设备信息或响应格式不正确');
          _channels = [];
        }
      } catch (e) {
        debugPrint('获取WVP设备信息或通道列表出错: $e');
        _channels = [];
      }
      
      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
        _isError = true;
        _errorMessage = '${LocaleKeys.loadingFailed.tr}: $e';
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    
    // 显示错误信息的通用组件
    Widget errorWidget = Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64,
            color: theme.colorScheme.error,
          ),
          const SizedBox(height: 16),
          Text(
            _errorMessage,
            style: theme.textTheme.titleMedium,
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: () {
              _initialize();
            },
            child: Text(LocaleKeys.retry.tr),
          ),
        ],
      ),
    );
    
    return Scaffold(
      appBar: AppBar(
        title: Text(_deviceName),
        actions: [
          if (_isLoggedIn && _channels.isNotEmpty)
            IconButton(
              icon: const Icon(Icons.refresh),
              onPressed: () {
                _initialize();
              },
            ),
        ],
      ),
      body: SafeArea(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : _isError
                ? errorWidget
                : _channels.isEmpty
                    ? Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.videocam_off,
                              size: 64,
                              color: theme.colorScheme.secondary.withOpacity(0.5),
                            ),
                            const SizedBox(height: 16),
                            Text(
                              LocaleKeys.noChannels.tr,
                              style: theme.textTheme.titleMedium,
                            ),
                            const SizedBox(height: 8),
                            Text(
                              LocaleKeys.noChannelsMessage.tr,
                              style: theme.textTheme.bodyMedium,
                            ),
                            if (_wvpDeviceId.isEmpty) ...[
                              const SizedBox(height: 16),
                              Container(
                                padding: const EdgeInsets.all(12),
                                decoration: BoxDecoration(
                                  color: theme.colorScheme.errorContainer,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Text(
                                  '${LocaleKeys.deviceId.tr}: ${LocaleKeys.notFound.tr}',
                                  style: TextStyle(
                                    color: theme.colorScheme.onErrorContainer,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ],
                          ],
                        ),
                      )
                    : _buildChannelList(theme),
      ),
    );
  }
  
  Widget _buildChannelList(ThemeData theme) {
    return ListView.builder(
      padding: const EdgeInsets.all(8),
      itemCount: _channels.length,
      itemBuilder: (context, index) {
        final channel = _channels[index];
        final isOnline = channel.status == 'ON';
        
        return Card(
          margin: const EdgeInsets.only(bottom: 16),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
            side: BorderSide(
              color: isOnline ? Colors.green.shade300 : Colors.grey.shade300,
              width: 1,
            ),
          ),
          child: InkWell(
            borderRadius: BorderRadius.circular(12),
            onTap: () {
              // 导航到视频播放页面
              Get.toNamed(
                Routes.deviceVideoPlay,
                arguments: {
                  'deviceName': _deviceName,
                  'channelName': channel.name,
                  'wvpDeviceId': _wvpDeviceId,
                  'channelId': channel.deviceId,
                },
              );
            },
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 通道名称和状态指示器
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          channel.name,
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: isOnline ? Colors.green.shade100 : Colors.grey.shade200,
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color: isOnline ? Colors.green.shade400 : Colors.grey.shade400,
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              isOnline ? Icons.check_circle : Icons.error_outline,
                              size: 16,
                              color: isOnline ? Colors.green.shade700 : Colors.grey.shade700,
                            ),
                            const SizedBox(width: 4),
                            Text(
                              isOnline ? LocaleKeys.channelOnline.tr : LocaleKeys.channelOffline.tr,
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: isOnline ? Colors.green.shade700 : Colors.grey.shade700,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  
                  const SizedBox(height: 12),
                  
                  // 通道基本信息
                  _buildInfoRow(LocaleKeys.channelId.tr, channel.deviceId),
                  _buildInfoRow(LocaleKeys.manufacturer.tr, channel.manufacturer ?? LocaleKeys.unknown.tr),
                  _buildInfoRow(LocaleKeys.model.tr, channel.model ?? LocaleKeys.unknown.tr),
                  _buildInfoRow(LocaleKeys.address.tr, channel.address ?? LocaleKeys.unknown.tr),
                  
                  // 通道网络信息
                  if (channel.ipAddress != null || channel.port != null)
                    Container(
                      margin: const EdgeInsets.only(top: 8),
                      padding: const EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: theme.colorScheme.surfaceVariant.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          if (channel.ipAddress != null)
                            _buildInfoRow(LocaleKeys.ipAddress.tr, channel.ipAddress!),
                          if (channel.port != null)
                            _buildInfoRow(LocaleKeys.port.tr, channel.port.toString()),
                        ],
                      ),
                    ),
                  
                  // 通道高级信息
                  Container(
                    margin: const EdgeInsets.only(top: 8),
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: theme.colorScheme.primaryContainer.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 云台类型
                        _buildInfoRow(
                          LocaleKeys.ptzTypeInfo.tr, 
                          channel.ptzType != null && channel.ptzType! > 0 
                              ? LocaleKeys.ptzTypeStandard.tr 
                              : LocaleKeys.ptzTypeNone.tr
                        ),
                        // 音频支持
                        _buildInfoRow(
                          LocaleKeys.hasAudio.tr, 
                          channel.hasAudio == 1 ? LocaleKeys.yes.tr : LocaleKeys.no.tr
                        ),
                        // 流ID
                        if (channel.streamId != null && channel.streamId!.isNotEmpty)
                          _buildInfoRow(LocaleKeys.streamId.tr, channel.streamId!),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 操作按钮
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      OutlinedButton.icon(
                        icon: const Icon(Icons.play_circle_outline, size: 18),
                        label: Text(LocaleKeys.videoMonitoring.tr),
                        style: OutlinedButton.styleFrom(
                          foregroundColor: theme.colorScheme.primary,
                          side: BorderSide(color: theme.colorScheme.primary),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        onPressed: () {
                          // 导航到视频播放页面
                          Get.toNamed(
                            Routes.deviceVideoPlay,
                            arguments: {
                              'deviceName': _deviceName,
                              'channelName': channel.name,
                              'wvpDeviceId': _wvpDeviceId,
                              'channelId': channel.deviceId,
                            },
                          );
                        },
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
  
  // 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              '$label:',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey[700],
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
} 